<template>
  <div class="report-behavior-container">
    <div class="page-header">
      <h1 class="page-title">不文明行为举报</h1>
      <p class="page-description">共同维护北京文化遗产，举报不文明行为</p>
    </div>

    <div class="report-section">
      <el-row :gutter="30">
        <el-col :xs="24" :md="16">
          <!-- 地图容器 -->
          <el-card class="map-card">
            <template #header>
              <div class="card-header">
                <h2>选择举报地点</h2>
                <p>请在地图上点击选择景点</p>
              </div>
            </template>
            <div id="reportMapView" class="map-container"></div>

            <!-- 选中景点信息 -->
            <div v-if="selectedSpot" class="selected-spot-info">
              <h3>已选择: {{ selectedSpot.SpotName }}</h3>
              <p v-if="selectedSpot.SpotType">类型: {{ selectedSpot.SpotType }}</p>
            </div>
            <div v-else class="no-selection-tip">
              <el-alert
                title="请在地图上选择一个景点以进行举报"
                type="info"
                :closable="false"
                show-icon
              />
            </div>
          </el-card>

          <el-card class="report-form-card">
            <template #header>
              <div class="card-header">
                <h2>举报不文明行为</h2>
                <p>请填写以下信息提交举报</p>
              </div>
            </template>

            <el-form :model="reportForm" label-position="top" ref="formRef" :rules="formRules">
              <el-form-item label="景点名称" prop="spotName">
                <el-input v-model="reportForm.spotName" placeholder="景点名称" disabled />
              </el-form-item>

              <el-form-item label="不文明行为类型" prop="type">
                <el-select v-model="reportForm.type" placeholder="请选择不文明行为类型" class="full-width">
                  <el-option label="刻画、涂污文物古迹" value="graffiti" />
                  <el-option label="攀爬文物古迹" value="climbing" />
                  <el-option label="触摸文物展品" value="touching" />
                  <el-option label="乱扔垃圾" value="littering" />
                  <el-option label="破坏植被" value="damaging_plants" />
                  <el-option label="喂食动物" value="feeding_animals" />
                  <el-option label="大声喧哗" value="noise" />
                  <el-option label="其他不文明行为" value="other" />
                </el-select>
              </el-form-item>

              <el-form-item label="发生时间" prop="date">
                <el-date-picker
                  v-model="reportForm.date"
                  type="datetime"
                  placeholder="选择日期和时间"
                  class="full-width"
                />
              </el-form-item>

              <el-form-item label="详细描述" prop="description">
                <el-input
                  v-model="reportForm.description"
                  type="textarea"
                  :rows="4"
                  placeholder="请详细描述不文明行为的具体情况"
                />
              </el-form-item>

              <el-form-item label="严重程度" prop="severity">
                <el-rate
                  v-model="reportForm.severity"
                  :colors="severityColors"
                  :texts="severityTexts"
                  show-text
                />
              </el-form-item>

              <el-form-item label="上传照片（可选）">
                <el-upload
                  action="#"
                  list-type="picture-card"
                  :auto-upload="false"
                  :on-change="handleImageChange"
                >
                  <el-icon><Plus /></el-icon>
                </el-upload>
              </el-form-item>

              <el-form-item label="联系方式（可选）">
                <el-input v-model="reportForm.contact" placeholder="留下您的联系方式，方便我们跟进处理" />
              </el-form-item>

              <el-form-item>
                <el-button type="primary" class="beijing-button full-width" @click="submitReport" :loading="submitting">提交举报</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>

        <el-col :xs="24" :md="8">
          <el-card class="info-card">
            <h3>举报须知</h3>
            <ul class="info-list">
              <li>
                <el-icon><InfoFilled /></el-icon>
                <span>您的举报将有助于保护北京文化遗产</span>
              </li>
              <li>
                <el-icon><InfoFilled /></el-icon>
                <span>请提供真实准确的信息</span>
              </li>
              <li>
                <el-icon><InfoFilled /></el-icon>
                <span>我们会对您的个人信息严格保密</span>
              </li>
              <li>
                <el-icon><InfoFilled /></el-icon>
                <span>举报信息将由专人核实处理</span>
              </li>
            </ul>

            <div class="contact-info">
              <h3>紧急联系方式</h3>
              <p><strong>文物保护热线：</strong> 12345</p>
              <p><strong>旅游投诉热线：</strong> 12301</p>
              <p><strong>警方报警电话：</strong> 110</p>
            </div>
          </el-card>

          <el-card class="recent-reports-card">
            <h3>近期举报处理情况</h3>
            <el-timeline>
              <el-timeline-item
                v-for="(activity, index) in activities"
                :key="index"
                :timestamp="activity.timestamp"
                :type="activity.type"
              >
                {{ activity.content }}
              </el-timeline-item>
            </el-timeline>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 提交成功对话框 -->
    <el-dialog
      v-model="showSuccessDialog"
      title="举报提交成功"
      width="30%"
      center
    >
      <div class="success-dialog-content">
        <el-icon class="success-icon"><CircleCheckFilled /></el-icon>
        <p>感谢您的举报，我们将尽快处理！</p>
        <p>举报编号：{{ reportId }}</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="resetForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { InfoFilled, Plus, CircleCheckFilled } from '@element-plus/icons-vue'
import { ElMessage, type FormInstance } from 'element-plus'
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import Graphic from '@arcgis/core/Graphic'
import SimpleMarkerSymbol from '@arcgis/core/symbols/SimpleMarkerSymbol'
import gaodeLayer from '@/utils/GaoDeBaseLayer'
import { useUserStore } from '@/stores/user'

// 用户信息

const userStore = useUserStore()

// 地图和图层
let view: __esri.MapView
let featureLayer: __esri.FeatureLayer

// 选中的景点
const selectedSpot = ref<any>(null)

// 表单引用
const formRef = ref<FormInstance>()

// 表单数据
const reportForm = ref({
  spotId: 0,
  spotName: '',
  type: '',
  date: new Date(),
  description: '',
  severity: 3,
  imageBase64: '',
  contact: ''
})

// 表单验证规则
const formRules = {
  spotName: [{ required: true, message: '请选择景点', trigger: 'blur' }],
  type: [{ required: true, message: '请选择不文明行为类型', trigger: 'change' }],
  date: [{ required: true, message: '请选择发生时间', trigger: 'change' }],
  description: [{ required: true, message: '请输入详细描述', trigger: 'blur' }],
  severity: [{ required: true, message: '请选择严重程度', trigger: 'change' }]
}

// 严重程度颜色和文本
const severityColors = ['#67C23A', '#E6A23C', '#F56C6C']
const severityTexts = ['轻微', '一般', '严重']

// 提交状态
const submitting = ref(false)
const showSuccessDialog = ref(false)
const reportId = ref('')

// 活动列表
const activities = ref([
  {
    content: '故宫某游客刻画墙壁，已处理并罚款',
    timestamp: '2023-10-15',
    type: 'danger'
  },
  {
    content: '八达岭长城游客乱扔垃圾，已清理完毕',
    timestamp: '2023-10-10',
    type: 'warning'
  },
  {
    content: '颐和园游客攀爬古建筑，已教育并警告',
    timestamp: '2023-10-05',
    type: 'success'
  }
])

// 获取行为类型文本
const getBehaviorTypeText = (type: string): string => {
  const typeMap: Record<string, string> = {
    'graffiti': '刻画涂污',
    'climbing': '攀爹古迹',
    'touching': '触摸展品',
    'littering': '乱扔垃圾',
    'damaging_plants': '破坏植被',
    'feeding_animals': '喝食动物',
    'noise': '大声嗥哇',
    'other': '其他行为'
  }
  return typeMap[type] || '未知类型'
}

// 初始化地图
const initMap = async () => {
  // 创建地图实例
  const map = new Map({
    basemap: {
      baseLayers: [gaodeLayer]
    }
  })

  // 创建地图视图
  view = new MapView({
    container: 'reportMapView',
    map: map,
    center: [116.3912, 39.9073], // 北京市中心坐标
    zoom: 12,
    popup: {
      dockEnabled: true,
      dockOptions: {
        buttonEnabled: false,
        breakpoint: false
      }
    }
  })

  // 创建要素图层
  featureLayer = new FeatureLayer({
    url: 'https://services7.arcgis.com/2irArZCaO94Te7ab/arcgis/rest/services/ScenicPointLayer/FeatureServer/0',
    outFields: ['*'],
    popupEnabled: false,
    renderer: {
      type: "unique-value",
      field: "SpotType",
      defaultSymbol: {
        type: "simple-marker",
        size: 14,
        color: [156, 156, 156, 0.8], // 默认灰色
        outline: {
          color: [255, 255, 255],
          width: 2
        }
      },
      uniqueValueInfos: [
        {
          value: "历史文化",
          symbol: {
            type: "simple-marker",
            size: 14,
            color: [225, 76, 66, 0.8], // 红色
            outline: {
              color: [255, 255, 255],
              width: 2
            }
          }
        },
        {
          value: "自然风光",
          symbol: {
            type: "simple-marker",
            size: 14,
            color: [56, 168, 0, 0.8], // 绿色
            outline: {
              color: [255, 255, 255],
              width: 2
            }
          }
        },
        {
          value: "休闲娱乐",
          symbol: {
            type: "simple-marker",
            size: 14,
            color: [0, 112, 255, 0.8], // 蓝色
            outline: {
              color: [255, 255, 255],
              width: 2
            }
          }
        }
      ]
    },
    // 添加标注
    labelingInfo: [{
      symbol: {
        type: "text",
        color: "#333333",
        haloColor: "#ffffff",
        haloSize: 2,
        font: {
          size: 12,
          weight: "normal"
        }
      },
      labelPlacement: "above-center",
      labelExpressionInfo: {
        expression: "$feature.SpotName"
      },
      minScale: 5000, // 当地图缩放到多少比例尺以内才显示标签
      maxScale: 0
    }]
  })

  // 将图层添加到地图
  map.add(featureLayer)

  // 添加点击事件监听器以选择要素
  view.on('click', async (event) => {
    const hitResults = (await view?.hitTest(event))?.results as __esri.MapViewGraphicHit[]
    const feature = hitResults.find((result) => result.layer?.id === featureLayer?.id)?.graphic

    if (feature) {
      selectedSpot.value = feature.attributes
      reportForm.value.spotId = feature.attributes.OBJECTID
      reportForm.value.spotName = feature.attributes.SpotName || `景点 #${feature.attributes.OBJECTID}`

      // 添加高亮效果
      view?.graphics.removeAll()
      const highlightSymbol = new SimpleMarkerSymbol({
        color: [255, 255, 255, 0.8],
        size: 16,
        outline: {
          color: [0, 122, 194],
          width: 3,
        },
      })

      const highlightGraphic = new Graphic({
        geometry: feature.geometry,
        symbol: highlightSymbol,
      })

      view?.graphics.add(highlightGraphic)
    } else {
      selectedSpot.value = null
      reportForm.value.spotId = 0
      reportForm.value.spotName = ''
      view?.graphics.removeAll()
    }
  })

  // 加载要素数据
  await loadFeatures()
}

// 加载要素数据
const loadFeatures = async () => {
  try {
    // 查询所有要素
    const query = featureLayer.createQuery()
    query.where = '1=1' // 查询所有记录
    query.outFields = ['*']

    const result = await featureLayer.queryFeatures(query)

    ElMessage.success(`已加载${result.features.length}个景点`)
  } catch (error) {
    console.error('加载景点数据失败', error)
    ElMessage.error('加载景点数据失败')
  }
}

// 处理图片变化
const handleImageChange = (file: any) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    if (e.target?.result) {
      reportForm.value.imageBase64 = e.target.result as string
    }
  }
  reader.readAsDataURL(file.raw)
}

// 生成随机举报ID
const generateReportId = () => {
  const timestamp = new Date().getTime()
  const random = Math.floor(Math.random() * 10000)
  return `BJ-${timestamp}-${random}`
}

// 提交举报
const submitReport = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请填写必填字段')
      return
    }

    if (!selectedSpot.value) {
      ElMessage.warning('请先选择一个景点')
      return
    }

    submitting.value = true

    try {
      // 生成举报ID
      const newReportId = generateReportId()
      reportId.value = newReportId

      // 定义举报数据类型
      interface ReportData {
        id: string;
        type: string;
        date: string;
        description: string;
        severity: number;
        imageBase64?: string;
        contact?: string;
        reporter: string;
        status: 'pending' | 'processed';
        processResult?: string;
        processTime?: string;
        reportTime: string;
      }

      // 准备举报数据
      const reportData: ReportData = {
        id: newReportId,
        type: reportForm.value.type,
        date: reportForm.value.date.toISOString(),
        description: reportForm.value.description,
        severity: reportForm.value.severity,
        imageBase64: reportForm.value.imageBase64,
        contact: reportForm.value.contact,
        reporter: userStore.currentUser?.username || '匿名用户',
        status: 'pending', // pending, processed
        reportTime: new Date().toISOString()
      }

      // 获取当前景点的不文明行为信息
      const query = featureLayer.createQuery()
      query.where = `OBJECTID = ${reportForm.value.spotId}`
      query.outFields = ['*']

      const result = await featureLayer.queryFeatures(query)
      const feature = result.features[0]

      if (!feature) {
        throw new Error('无法获取景点信息')
      }

      // 解析现有的不文明行为信息
      let reports: ReportData[] = []
      try {
        if (feature.attributes.UncivilizedBehaviorReportMessageJSON) {
          const parsedData = JSON.parse(feature.attributes.UncivilizedBehaviorReportMessageJSON)
          if (Array.isArray(parsedData)) {
            reports = parsedData as ReportData[]
          }
        }
      } catch (e) {
        console.error('解析不文明行为信息失败', e)
        reports = []
      }

      // 添加新的举报
      reports.push(reportData)

      // 计算待处理的举报数量
      const pendingReports = reports.filter(report => report.status === 'pending')
      const pendingCount = pendingReports.length

      console.log(`景点 #${reportForm.value.spotId} 的待处理举报数量为 ${pendingCount}`)

      // 更新景点数据
      const attributes = {
        OBJECTID: reportForm.value.spotId,
        UncivilizedBehaviorReportMessageJSON: JSON.stringify(reports),
        UncivilizedBehaviorReportCount: pendingCount // 只计算待处理的举报数量
      }

      // 创建更新图形
      const updateFeature = new Graphic({
        attributes: attributes
      })

      // 应用编辑
      console.log('开始提交举报数据', updateFeature)
      try {
        const updateResult = await featureLayer.applyEdits({
          updateFeatures: [updateFeature]
        })

        console.log('提交举报数据结果', updateResult)

        if (updateResult.updateFeatureResults && updateResult.updateFeatureResults.length > 0) {
          // 更新成功
          showSuccessDialog.value = true

          // 添加到活动列表中（可选）
          const behaviorTypeText = getBehaviorTypeText(reportForm.value.type)
          activities.value.unshift({
            content: `${reportForm.value.spotName}发生${behaviorTypeText}，已提交待处理`,
            timestamp: new Date().toLocaleDateString('zh-CN'),
            type: 'warning'
          })

          // 保持活动列表最多显示5条
          if (activities.value.length > 5) {
            activities.value.pop()
          }
        } else {
          console.error('更新结果不包含有效数据', updateResult)
          throw new Error('更新景点数据失败')
        }
      } catch (error) {
        console.error('应用编辑时发生错误', error)
        throw error
      }
    } catch (error) {
      console.error('提交举报失败', error)
      ElMessage.error('提交举报失败')
    } finally {
      submitting.value = false
    }
  })
}

// 重置表单
const resetForm = () => {
  reportForm.value = {
    spotId: 0,
    spotName: '',
    type: '',
    date: new Date(),
    description: '',
    severity: 3,
    imageBase64: '',
    contact: ''
  }

  selectedSpot.value = null
  view?.graphics.removeAll()
  showSuccessDialog.value = false
}

onMounted(() => {
  initMap()
})
</script>

<style scoped>
.report-behavior-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  text-align: center;
  margin-bottom: 40px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.page-title {
  font-size: 32px;
  color: #c62f2f;
  margin-bottom: 10px;
  font-weight: bold;
}

.page-description {
  font-size: 16px;
  color: #666;
  max-width: 600px;
  margin: 0 auto;
}

.report-section {
  margin-bottom: 50px;
}

.map-card,
.report-form-card,
.info-card,
.recent-reports-card {
  margin-bottom: 30px;
  border: none;
}

.map-container {
  height: 400px;
  width: 100%;
  position: relative;
  border-radius: 4px;
  overflow: hidden;
}

.selected-spot-info {
  background-color: #f0f9eb;
  padding: 15px;
  border-radius: 4px;
  margin-top: 15px;
  border-left: 4px solid #67c23a;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.selected-spot-info h3 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 16px;
  color: #303133;
}

.selected-spot-info p {
  margin: 5px 0;
  color: #606266;
}

.no-selection-tip {
  margin-top: 15px;
}

.card-header {
  margin-bottom: 20px;
}

.card-header h2 {
  font-size: 22px;
  color: #c62f2f;
  margin-bottom: 5px;
}

.card-header p {
  color: #666;
  margin: 0;
}

.full-width {
  width: 100%;
}

.beijing-button {
  background-color: #c62f2f;
  border-color: #c62f2f;
  padding: 12px 24px;
  font-size: 16px;
}

.beijing-button:hover {
  background-color: #a52222;
  border-color: #a52222;
}

.info-card,
.recent-reports-card {
  padding: 20px;
}

.info-card h3,
.recent-reports-card h3 {
  font-size: 18px;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.info-list {
  list-style: none;
  padding: 0;
  margin-bottom: 30px;
}

.info-list li {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
}

.info-list li .el-icon {
  color: #c62f2f;
  margin-right: 10px;
  font-size: 18px;
  margin-top: 2px;
}

.info-list li span {
  color: #666;
  line-height: 1.5;
}

.contact-info {
  margin-top: 30px;
}

.contact-info p {
  margin-bottom: 10px;
  color: #666;
}

.recent-reports-card {
  margin-top: 30px;
}

/* 成功对话框样式 */
.success-dialog-content {
  text-align: center;
  padding: 20px 0;
}

.success-icon {
  font-size: 60px;
  color: #67c23a;
  margin-bottom: 20px;
}

.success-dialog-content p {
  margin: 10px 0;
  font-size: 16px;
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: center;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .report-behavior-container {
    padding: 10px;
  }

  .map-container {
    height: 300px;
  }
}
</style>
